//
//  VideoViewController.m
//  HGY
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 顾成辉. All rights reserved.
//

#import "VideoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ThirdModel.h"
#import <MediaPlayer/MediaPlayer.h>

#import "thirdSQManager.h"

//#import "ThirdManager.h"

@interface VideoViewController ()

//@property (nonatomic, strong) AVPlayer *player; // 播放器对象
//@property (nonatomic, strong) UIView *container; // 播放器容器
//@property (nonatomic, strong) UIButton *playOrPause; // 播放暂停按钮
//@property (nonatomic, strong) UIProgressView *progress; // 播放进度
//@property (nonatomic, strong) UILabel *startLabel;// 开始时间
//@property (nonatomic, strong) UILabel *finishLabel;// 结束时间
//@property (nonatomic, strong) NSArray *picArray; // labe数组
@property (nonatomic, strong) UILabel *contentLabel;// 视频
@property (nonatomic, strong) MPMoviePlayerController *moviePlayer;
@property (nonatomic, strong) UILabel *nameLabel;// 内容
@property (nonatomic, strong) UILabel *titleLabel;// 标题


@property (nonatomic, strong) VideoViewController *VideoVC;


@property(nonatomic,retain)NSMutableArray *dataArray;
@property (nonatomic, strong) UITableView *tableView;


@property (nonatomic, assign)BOOL isBool;

@end

@implementation VideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [self viewLayout];
//    [self removeObserverFromPlayerItem:self.player.currentItem];
//    [self removeNotification];
    
    
//    self.navigationItem.title = self.thirdmodel.title;
    
    [SVProgressHUD show];

    // 播放
    [self.moviePlayer play];
    // 添加通知
    [self addNotification];
    
    [self addLabel];

    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImage *leftButtonImage=[UIImage imageNamed:@"返回"];
    
    leftButtonImage = [leftButtonImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithImage:leftButtonImage style:UIBarButtonItemStyleDone target:self action:@selector(doback)];
    
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"收藏" style:(UIBarButtonItemStylePlain) target:self action:@selector(actionRightButton:)];
    self.navigationItem.rightBarButtonItem = rightButton;
  
    _isBool = NO;
}
- (void)actionRightButton:(UIBarButtonItem *)button
{

#pragma  mark -- 插入数据库
    [[thirdSQManager shareManager] createTable];
    ThirdModel *model = [[ThirdModel alloc] init];
    model.title = self.thirdmodel.title;
    model.playUrl = self.thirdmodel.playUrl;
    model.coverForDetail = self.thirdmodel.coverForDetail;
    
    
    if (model.title.length != 0 && model.playUrl.length != 0) {
        NSMutableArray *array = [[thirdSQManager shareManager] queryAll];
        for (ThirdModel *model1 in array) {
            if ([model1.title isEqualToString:self.thirdmodel.title]) {
                _isBool = YES;
            }
        }
      
    }
    
    if (_isBool == YES) {
        UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经收藏过了" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [view show];
        return;
        
        
    } else {
        [[thirdSQManager  shareManager] insetWith:model];
        UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [view show];
        
    }

}

//返回
-(void)doback
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
    
}


- (void)dealloc
{
    // 移除所有通知监控
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

// 获取网络路径
- (NSURL *)getNetworkUrl
{
    NSString *string = self.thirdmodel.playUrl;
    
    string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:string];
    return url;
}

- (MPMoviePlayerController *)moviePlayer
{
    if (!_moviePlayer) {
        NSURL *url = [self getNetworkUrl];
        self.moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:url];
        self.moviePlayer.view.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        
        self.moviePlayer.view.frame = CGRectMake(0 * kWidth, 30 * kHeight, kScreenWidth, kScreenHeight / 2);
        [SVProgressHUD dismiss];
//
////        self.moviePlayer.view.layer.borderWidth = 5;   //边框宽度
//
//        
        [self.view addSubview:_moviePlayer.view];
        
        
        
        
    }

    return _moviePlayer;
}

- (void)addLabel
{
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 *kWidth, 430 *kHeight, kScreenWidth - 30 *kWidth, 100 *kHeight)];
//    self.nameLabel.backgroundColor = [UIColor redColor];
    
    self.nameLabel.text = self.thirdmodel.Description;
    
    
    NSString *content = self.thirdmodel.Description;
    CGFloat height = [self adjustSubviewsWithContent:content];
    
    CGRect newFrame = self.VideoVC.nameLabel.frame;
    newFrame.size.height = height;
    self.VideoVC.nameLabel.frame = newFrame;
    
    self.VideoVC.nameLabel.text = content;
    
    self.nameLabel.numberOfLines = 0;
    
 
    self.nameLabel.textAlignment = NSTextAlignmentNatural;

    [self.view addSubview:self.nameLabel];
    
    
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 *kWidth, 350 *kHeight, 300 *kWidth, 100 *kHeight)];
    self.titleLabel.text = self.thirdmodel.title;
    [self.view addSubview:self.titleLabel];
    
}

- (CGFloat)adjustSubviewsWithContent:(NSString *)content
{
    //计算活动内容的高度
    CGRect frame = [content boundingRectWithSize:CGSizeMake(self.nameLabel.width *kWidth, 10000 * kHeight) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17] forKey:NSFontAttributeName] context:nil];
    // 更改label高度
    self.nameLabel.height = frame.size.height;
    
    return self.nameLabel.height;
    
}


// 添加通知监控
-(void)addNotification{

    NSNotificationCenter *notificationCenter=[NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayer];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
    
}
-(void)mediaPlayerPlaybackStateChange:(NSNotification *)notification{
    switch (self.moviePlayer.playbackState) {
        case MPMoviePlaybackStatePlaying:
            NSLog(@"正在播放...");
            break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"暂停播放.");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"停止播放.");
            break;
        default:
            NSLog(@"播放状态:%li",self.moviePlayer.playbackState);
            break;
    }
}

-(void)mediaPlayerPlaybackFinished:(NSNotification *)notification{
    NSLog(@"播放完成.%li",self.moviePlayer.playbackState);
}


- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    [self.moviePlayer pause];
}





//- (void)viewLayout
//{



//    self.navigationController.navigationBar.translucent = NO;
//    self.container = [[UIView alloc] initWithFrame:CGRectMake(0, 30, kScreenWidth, kScreenWidth - 100)];
//    self.container.backgroundColor = [UIColor redColor];
////    UITapGestureRecognizer *containerTapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(screenDidTap:)];
////    [self.container addGestureRecognizer:containerTapGesture];
//    [self.view addSubview:self.container];
//
//    
//    
//    
//    // 标题
//    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 240, 30)];
//    //    self.nameLabel.backgroundColor = [UIColor redColor];
//    
//    self.nameLabel.text = self.thirdmodel.title;
//    self.contentLabel.numberOfLines = 0;
//    
//    [self.view addSubview:self.nameLabel];
//   
//    // 进度条
//    self.progress = [[UIProgressView alloc] initWithProgressViewStyle:(UIProgressViewStyleDefault)];
//    self.progress.frame = CGRectMake(80, self.container.bottom - 20, kScreenWidth - 160, 10);
//    self.progress.progressTintColor = [UIColor blackColor];
//    self.progress.trackTintColor = [UIColor redColor];
//
//    [self.view addSubview:self.progress];
//
//
//    // 播放暂停
//    self.playOrPause = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.playOrPause.frame = CGRectMake(5 , self.progress.bottom - 10, 20, 20);
//    [self.playOrPause addTarget:self action:@selector(actionPlayOrPause:) forControlEvents:UIControlEventTouchUpInside];
//
//    [self.view addSubview:self.playOrPause];
//    [self.playOrPause setImage:[UIImage imageNamed:@"4"] forState:(UIControlStateNormal)];
//    
//    [self setupUI];
//    [self.player play];
//    
//    
//    // 开始时间
//    self.startLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.playOrPause.left + 30, self.progress.bottom - 10, 40, 20)];
////    self.startLabel.backgroundColor = [UIColor redColor];
//    self.startLabel.font = [UIFont systemFontOfSize:12];
//
//    [self.view addSubview:self.startLabel];
//    
//    // 结束时间
//    self.finishLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.progress.right + 5, self.progress.bottom - 10, 45, 20)];
////    self.finishLabel.backgroundColor = [UIColor redColor];
//    self.finishLabel.font = [UIFont systemFontOfSize:12];
//    [self.view addSubview:self.finishLabel];
    

    
//   // 内容
//    self.contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.playOrPause.bottom + 50, kScreenWidth, kScreenWidth  - 270)];
////    self.picArray = [NSArray arrayWithObjects:@"  俱乐部三明治，也叫会所三明治，一般用煎蛋、火腿、蔬菜、奶酪、烟肉和番茄等各式食材制作而成。短片画风清新地将每个制作步骤都展示得十分清楚。", @"  著名的玛莎百货关于食材的这一系列广告又出新的了，foodfilm 制作的这个系列不仅稳定高产，每一次都还能再2带来一些新意。这一支短片是结合了秋季的当季食材，讲述了它们的冒险", @"  秋风起，蟹脚痒”入秋之后的九十月份正是吃螃蟹的好季节，此时的螃蟹肉厚肥嫩，色香味美。甚至有食家言“秋天以吃螃蟹为最隆重之事”。在这个正好的季节，不妨跟着短片了解一下螃蟹简单美味的做法", @"  甜甜圈这项深受甜食爱好者偏爱的小甜点，由面粉、砂糖、奶油和鸡蛋混合后经过油炸而成。最普通的环形，中间加入奶油、蛋浆等甜馅料。而这几年随着甜甜圈的火热，更是发展出了各式各样的新味道。", @"  冰皮月饼是一种新派中秋月饼，外皮以糯米粉、面粉制成，馅料除了传统的莲蓉等，也有水果等新鲜口味。跟着短片一起看看具体是怎么制作的吧。", @"  玛格丽特是一款广受欢迎的经典鸡尾酒，作为1949年全美鸡尾酒大赛的冠军，有着“鸡尾酒之后”的美称。玛格丽特的名字源自创作者逝去的女友，据说因为女友生前喜欢吃咸的，所以他加上一圈盐以表思念。", @"  分子料理是近几年美食的新流行，是将化学理论用于煮食之上，将食物的分子结构重组，以创造出全新的食材和口味来。短片是分子冰淇淋神奇的制作过程。", @"  Alinea Restaurant 是位于美国芝加哥的一家餐厅，邀请到大提琴手 Katalin von Walterskirchen 之后，拍摄了这样一支琴声与美食碰撞的短片，餐厅的气质、高格调都在其中流露出来了。", @"  在卡夫这个 Miracle Whip 沙拉酱广告中，丧心病狂地列举了来自十几个国家和地区 BBQ 的种类及其配搭。不得不说，看完这个广告后整个内心是非常崩溃的。", @"在这支「Behind the Pin」系列的集锦里，展示了许多奇妙有趣的可爱美味。比如肉丸木乃伊、迷你玉米卷杯、名字很有韵律的empana-ta-da（看上去是某种饺子）、棉花糖串等等。", nil];
////    
////    self.contentLabel.text = self.picArray[self.index];
//    
//    self.contentLabel.text = self.thirdmodel.description;
//
//    
//
//    [self.view addSubview:self.contentLabel];
    
    
//}





//
//- (void)screenDidTap:(UITapGestureRecognizer *)sender{
//    if (self.progress.alpha == 0) {
//        
//        self.progress.alpha = 1;
//        self.playOrPause.alpha = 1;
//        self.startLabel.alpha = 1;
//        self.finishLabel.alpha = 1;
//    }else{
//        
//        self.progress.alpha = 0;
//         self.playOrPause.alpha = 0;
//        self.startLabel.alpha = 0;
//        self.finishLabel.alpha = 0;
//    }
//    
//}
//
//
//
//
//
//- (void)setupUI
//{
//    // 创建播放器层
//    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
//    playerLayer.frame = self.container.frame;
//    //    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect; //视频填充模式
//    [self.container.layer addSublayer:playerLayer];
//}
//
//- (AVPlayer *)player
//{
//    if (!_player) {
//        AVPlayerItem *playerItem = [self getPlayItem:0];
//        _player = [AVPlayer playerWithPlayerItem:playerItem];
//        [self addProgressObserver];
//        [self addObserverToPlayerItem:playerItem];
//    }
//    return _player;
//}
//
//// 根据视频索引取得AVPlayerItem对象
//- (AVPlayerItem *)getPlayItem:(int)videoIndex{
//    
//
//    NSString *string = self.thirdmodel.playUrl;
//    
//    
//
//    string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSURL *url = [NSURL URLWithString:string];
//    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
//    return playerItem;
//}
//
//
//#pragma mark -- 添加播放器通知
//- (void)addNotification{
//    // 给AVPlayerItem添加播放完成通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
//    
//}
//
//- (void)removeNotification
//{
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}
//
//- (void)playbackFinished:(NSNotification *)notification
//{
//    NSLog(@"视频播放完成");
//}
//
//#pragma mark -- 监控(给播放器添加进度更新)
//- (void)addProgressObserver
//{
//    AVPlayerItem *playerItem = self.player.currentItem;
//    UIProgressView *progress = self.progress;
//    // 在这里设置每秒执行一次
//    
//    // block中必须修饰
//    __block VideoViewController *viewVC = self;
//    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
//        float current = CMTimeGetSeconds(time);
//        float total = CMTimeGetSeconds([playerItem duration]);
//        NSLog(@"当前已经播放%.2fs", current);
//        if (current) {
//            [progress setProgress:(current/total) animated:YES];
//        }
//        [SVProgressHUD dismiss];
//        
//        
//        
//        if ((int)current % 60 < 10) {
//            viewVC.startLabel.text = [NSString stringWithFormat:@"0%d:0%d",(int)current / 60, (int)current %60];
//            
//        }else {
//            viewVC.startLabel.text = [NSString stringWithFormat:@"0%d:0%d",(int)current / 60, (int)current %60];
//            
//        }
//        
//        if ((int)total % 60 < 10) {
//            viewVC.finishLabel.text = [NSString stringWithFormat:@"0%d:0%d",(int)total / 60, (int)total %60];
//            
//        }else {
//            viewVC.finishLabel.text = [NSString stringWithFormat:@"0%d:0%d",(int)total / 60, (int)total %60];
//            
//        }
//
//        
//
//        
//    }];
//
//
//    
//
//}
//
//#pragma mark -- 给AVPlayerItem添加监控
//- (void)addObserverToPlayerItem:(AVPlayerItem *)playerItem
//{
//    // 监控状态属性, 注意AVPlayer也有一个status属性, 通过监控它的status也可以获得播放状态
//    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
//    // 监控网络加载情况属性
//    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
//}
//- (void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem
//{
//    [playerItem removeObserver:self forKeyPath:@"status"];
//    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
//}
//
///*
// 通过KVO监控播放器状态
// @param keyPath 监控属性
// @param object 监视器
// @param change 状态改变
// @param context 上下文
// */
//
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
//{
//    AVPlayerItem *playerItem = object;
//    if ([keyPath isEqualToString:@"status"]) {
//        AVPlayerStatus status = [[change objectForKey:@"new"] intValue];
//        if (status == AVPlayerStatusReadyToPlay) {
//            NSLog(@"正在播放..., 视频总长度:%.2f", CMTimeGetSeconds(playerItem.duration));
//        }
//    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
//        NSArray *array = playerItem.loadedTimeRanges;
//        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue]; // 本次缓冲时间范围
//        float startSeconds = CMTimeGetSeconds(timeRange.start);
//        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
//        NSTimeInterval totalBuffer = startSeconds + durationSeconds; // 缓冲总长度
//        NSLog(@"共缓存:%.2f", totalBuffer);
//    }
//    
//    
//    
//
//}
//
//#pragma mark -- UI事件(点击播放/暂停按钮)
//- (void)actionPlayOrPause:(UIButton *)sender
//{
//    if (self.player.rate == 0) { // 说明在暂停
//        [sender setImage:[UIImage imageNamed:@"4"] forState:(UIControlStateNormal)];
//        [self.player play];
//    } else if (self.player.rate == 1) { // 正在播放
//        [self.player pause];
//        [sender setImage:[UIImage imageNamed:@"2"] forState:(UIControlStateNormal)];
//
//    }
//}













- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
